<template>
  <div class="loan-form">
<!--    <div style="display: flex;flex-direction: row;align-items: center;color: #409eff;cursor: pointer" @click="backHome">-->
<!--      <el-icon>-->
<!--        <House color="#409eff" size="20"/>-->
<!--      </el-icon>-->
<!--      <span>首页</span>-->
<!--    </div>-->
    <div style="background-color: #eeeeee;padding: 0 2%;width: 96%">
      <el-form
          label-position="top"
          ref="formRef"
          :model="formData"
          :rules="rules"
          label-width="140"
          class="loan-form-container">

        <div style="background-color: white;border-radius: 10px;padding: 5px 5px;margin-top: 5px">
          <!-- 基本信息部分 -->
          <el-divider content-position="center">基本信息</el-divider>

<!--          <el-form-item label="业务员" prop="userId">-->
<!--            <el-select-->
<!--                v-model="formData.userId"-->
<!--                placeholder="请选择业务员"-->
<!--                filterable-->
<!--                remote-->
<!--                :remote-method="handleSearch"-->
<!--                :loading="loading">-->
<!--              <el-option-->
<!--                  v-for="item in salesmanList"-->
<!--                  :key="item.id"-->
<!--                  :label="item.nickname"-->
<!--                  :value="item.id"-->
<!--              />-->
<!--            </el-select>-->
<!--          </el-form-item>-->
          <el-form-item label="车辆类型" prop="vehicleType">
            <el-select v-model="formData.vehicleType" placeholder="请选择车辆类型">
              <el-option label="二手乘用车" value="二手乘用车"/>
              <el-option label="新车乘用车" value="新车乘用车"/>
              <el-option label="二手商用车" value="二手商用车"/>
              <el-option label="新车商用车" value="新车商用车"/>
            </el-select>
          </el-form-item>

          <!--   身份证上传   -->
          <el-form-item label="身份证正面照片" prop="idCardPhotos" required>
            <el-upload
                ref="uploadRef0"
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :limit="1"
                list-type="picture-card"
                :on-change="handleUploadSuccess0"
                @remove="handleRemoveFile0"
                :on-exceed="handleExceed0"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>

          </el-form-item>

          <el-form-item label="身份证反面照片" prop="idCardPhotos" required>
            <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :limit="1"
                list-type="picture-card"
                :on-change="handleUploadSuccess1"
                @remove="handleRemoveFile1"
                :on-exceed="handleExceed1"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>


          <el-form-item label="客户姓名" prop="customerName">
            <el-input v-model="formData.customerName" placeholder="请输入客户姓名"/>
          </el-form-item>
          <el-form-item label="身份证号码" prop="idNumber">
            <el-input v-model="formData.idNumber" maxlength="18" placeholder="请输入身份证号码"/>
          </el-form-item>
          <!--  新增户籍地址    -->
          <el-form-item label="户籍地址" prop="address">
            <el-input v-model="formData.address"  placeholder="请输入户籍地址"/>
          </el-form-item>
          <el-form-item label="实际居住地址" prop="realAddress">
            <el-cascader
                clearable
                class="realClass"
                popper-class="train-tree"
                v-model="selectedArea1"
                :options="regionData"
                :props="{
                    expandTrigger: 'hover',
                    label: 'label',  // 指定显示文本的字段名
                    value: 'label',   // 指定值的字段名
                    children: 'children' // 指定子节点的字段名
                 }"
                @change="handleAreaChange1"
                placeholder="请选择实际居住地址"
                style="width: 100%; margin-bottom: 10px;"
            />
            <el-input v-model="formData.detailAddress" placeholder="请输入详细地址"/>
          </el-form-item>
          <el-form-item label="手机号码" prop="phoneNumber">
            <el-input v-model="formData.phoneNumber" maxlength="11" placeholder="请输入手机号码"/>
          </el-form-item>

          <el-form-item label="工作单位" prop="workUnit">
            <el-input v-model="formData.workUnit" placeholder="请输入工作单位"/>
          </el-form-item>

          <el-form-item label="工作地址" prop="workplace">
            <el-cascader
                clearable
                class="realClass"
                popper-class="train-tree"
                v-model="selectedArea2"
                :options="regionData"
                :props="{
                    expandTrigger: 'hover',
                    label: 'label',  // 指定显示文本的字段名
                    value: 'label',   // 指定值的字段名
                    children: 'children' // 指定子节点的字段名
                 }"
                @change="handleAreaChange2"
                placeholder="请选择工作地址"
                style="width: 100%; margin-bottom: 10px;"
            />
            <el-input v-model="formData.workDetailPlace" placeholder="请输入详细工作地址"/>
          </el-form-item>
          <!--          <el-form-item label="详细地址" prop="workDetailPlace">-->
          <!--            <el-input v-model="formData.workDetailPlace"  placeholder="请输入详细地址"/>-->
          <!--          </el-form-item>-->
          <!--          <el-form-item label="单位地址" prop="workAddress">-->
          <!--            <el-input v-model="formData.workAddress" />-->
          <!--          </el-form-item>-->
          <el-form-item label="本月收入(元)" prop="monthlyIncome">
            <el-input v-model="formData.monthlyIncome" type="number" placeholder="请输入本月收入"/>
          </el-form-item>

          <!--          <el-form-item label="工作年限" prop="workYears">-->
          <!--            <el-input v-model="formData.workYears" type="number" />-->
          <!--          </el-form-item>-->
        </div>

        <!--  车辆信息    -->
        <div style="background-color: white;border-radius: 10px;padding: 5px 5px;margin-top: 10px">
          <el-divider content-position="center">车辆信息</el-divider>
          <el-form-item label="上牌地" prop="registrationPlace">
            <el-input v-model="formData.registrationPlace" placeholder="请输入上牌地"/>
          </el-form-item>
          <!--        <el-form-item label="车架号" prop="vinCode">-->
          <!--          <el-input v-model="formData.vinCode" @blur="checkVinCode" maxlength="17" placeholder="请输入17位车架号" />-->
          <!--        </el-form-item>-->

          <el-form-item label="公里数(Km)" prop="mileage">
            <el-input v-model="formData.mileage" type="number" placeholder="请输入公里数"/>
          </el-form-item>
          <el-form-item label="贷款金额(元)" prop="loanAmount">
            <el-input v-model="formData.loanAmount" type="number" @blur="calculateLoanParams" placeholder="请输入贷款金额"/>
          </el-form-item>

          <el-form-item label="贷款期数(月)" prop="loanTerm">
            <el-input v-model="formData.loanTerm" type="number" @blur="calculateLoanParams" placeholder="请输入贷款期数"/>
          </el-form-item>

          <el-form-item label="年利率(%)" prop="annualRate">
            <el-input v-model="formData.annualRate" @blur="calculateLoanParams" placeholder="请输入年利率"/>
          </el-form-item>

          <el-form-item label="万元系数" prop="coefficient">
            <el-input disabled v-model="formData.coefficient" type="number"/>
          </el-form-item>
          <el-form-item label="月供试算" prop="monthlyPayment">
            <el-input disabled v-model="formData.monthlyPayment" type="number"/>
          </el-form-item>

        </div>

        <div style="background-color: white;border-radius: 10px;padding: 5px 5px;margin-top: 10px">
          <!--    婚姻状况  -->
          <el-divider content-position="center">婚姻状况</el-divider>
          <el-form-item label="婚姻状况" prop="maritalStatus">
            <el-select v-model="formData.maritalStatus" placeholder="请选择婚姻状况">
              <el-option label="已婚" value="已婚"/>
              <el-option label="未婚" value="未婚"/>
              <el-option label="离异" value="离异"/>
              <el-option label="丧偶" value="丧偶"/>
            </el-select>
          </el-form-item>
        </div>


        <div style="background-color: white;border-radius: 10px;padding: 5px 5px;margin-top: 10px">
          <!-- 联系人信息 -->
          <el-divider content-position="center">联系人信息</el-divider>

          <el-form-item label="亲友联系人姓名" prop="contactName">
            <el-input v-model="formData.contactName" placeholder="请输入亲友联系人姓名"/>
          </el-form-item>

          <el-form-item label="亲友联系人手机号" prop="contactPhone">
            <el-input v-model="formData.contactPhone" maxlength="11" placeholder="请输入亲友联系人手机号"/>
          </el-form-item>

          <el-form-item label="亲友联系人与客户关系" prop="contactRelation">
            <el-select v-model="formData.contactRelation" placeholder="请选择亲友联系人与客户关系">
              <el-option label="父子(女)" value="父子(女)"/>
              <el-option label="母子(女)" value="母子(女)"/>
              <el-option label="兄弟(姐妹)" value="兄弟(姐妹)"/>
              <el-option label="其他亲戚" value="其他亲戚"/>
              <el-option label="朋友" value="朋友"/>
              <el-option label="同事" value="同事"/>
              <el-option label="同学" value="同学"/>
            </el-select>
          </el-form-item>

          <el-form-item label="其他亲友联系人姓名" prop="otherContactName">
            <el-input v-model="formData.otherContactName"  placeholder="请输入其他亲友联系人姓名"/>
          </el-form-item>

          <el-form-item label="其他亲友联系人手机号" prop="otherContactPhone">
            <el-input v-model="formData.otherContactPhone" maxlength="11" placeholder="请输入其他亲友联系人手机号"/>
          </el-form-item>

          <el-form-item label="其他亲友联系人与客户关系" prop="otherContactRelation">
            <el-select v-model="formData.otherContactRelation" placeholder="请选择其他亲友联系人与客户关系">
              <el-option label="父子(女)" value="父子(女)"/>
              <el-option label="母子(女)" value="母子(女)"/>
              <el-option label="兄弟(姐妹)" value="兄弟(姐妹)"/>
              <el-option label="其他亲戚" value="其他亲戚"/>
              <el-option label="朋友" value="朋友"/>
              <el-option label="同事" value="同事"/>
              <el-option label="同学" value="同学"/>
            </el-select>
          </el-form-item>

        </div>


        <div style="background-color: white;border-radius: 10px;padding: 5px 5px;margin-top: 10px">
          <el-divider content-position="center">驾驶证信息</el-divider>
          <el-form-item label="驾驶证持证人信息" prop="driverPersonMsg">
            <el-select v-model="formData.driverPersonMsg" placeholder="请选择持有人信息">
              <el-option label="本人" value="本人"/>
              <el-option label="学车证明" value="学车证明"/>
              <el-option label="配偶" value="配偶"/>
              <el-option label="直系亲属" value="直系亲属"/>
              <el-option label="其他" value="其他"/>
            </el-select>
          </el-form-item>

        </div>

        <div style="background-color: white;border-radius: 10px;padding: 5px 5px;margin-top: 10px">
          <!-- 证件上传 -->
          <el-divider content-position="center">影像上传</el-divider>

          <!--        <el-form-item label="身份证" prop="idCardPhotos" required>-->
          <!--          <el-upload-->
          <!--              class="upload-demo"-->
          <!--              action="#"-->
          <!--              :auto-upload="false"-->
          <!--              :limit="2"-->
          <!--              list-type="picture-card"-->
          <!--              :on-change="handleUploadSuccess1"-->
          <!--              @remove="handleRemoveFile1"-->
          <!--              :on-exceed="handleExceed1"-->
          <!--          >-->
          <!--            <el-icon><Plus /></el-icon>-->
          <!--          </el-upload>-->
          <!--        </el-form-item>-->

          <el-form-item label="上传驾驶证" prop="driverLicense" required>
            <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :limit="1"
                list-type="picture-card"
                :on-change="handleUploadSuccess2"
                @remove="handleRemoveFile2"
                :on-exceed="handleExceed2"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="上传车辆登记证书" prop="vehicleRegistration" required>
            <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :limit="1"
                list-type="picture-card"
                :on-change="handleUploadSuccess3"
                @remove="handleRemoveFile3"
                :on-exceed="handleExceed3"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="上传车辆行驶证" prop="vehicleLicense" required>
            <el-upload
                ref="uploadRef4"
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :limit="1"
                list-type="picture-card"
                :on-change="handleUploadSuccess4"
                @remove="handleRemoveFile4"
                :on-exceed="handleExceed4"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="上传证明关系" prop="relationshipProof">
            <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :limit="1"
                list-type="picture-card"
                :on-change="handleUploadSuccess5"
                @remove="handleRemoveFile5"
                :on-exceed="handleExceed5">
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>

          <el-form-item label="收入证明" prop="incomeProof">
            <el-upload
                class="upload-demo"
                action="#"
                :auto-upload="false"
                :limit="2"
                list-type="picture-card"
                :on-change="handleUploadSuccess6"
                @remove="handleRemoveFile6"
                :on-exceed="handleExceed6"
            >
              <el-icon>
                <Plus/>
              </el-icon>
            </el-upload>
          </el-form-item>
        </div>


        <el-form-item>
          <div style="width: 100%;text-align: center;margin: 5px 0">
            <el-button type="primary" @click="submitForm" :disabled="submitLoading" :loading="submitLoading">提交申请</el-button>
          </div>
        </el-form-item>

      </el-form>
    </div>
  </div>
</template>

<script setup>
// 修改引入方式为
import {
  provinceAndCityData,
  pcTextArr,
  regionData,
  pcaTextArr,
  codeToText,
} from "element-china-area-data";

import {ref, reactive, onMounted} from 'vue'
import {Plus, House} from '@element-plus/icons-vue'
import {ElMessage,ElLoading} from 'element-plus'
import {useRoute, useRouter} from "vue-router";

const router = useRouter()
import axios from 'axios'

// 直接定义 API 基础 URL
const API_BASE_URL = '/api'

const salesmanList = ref([])
const loading = ref(false)
// 获取客户群体列表
const customerList = ref([])


// 获取业务员列表
const getSalesmanList = async () => {
  loading.value = true
  try {
    const response = await axios.get(`${API_BASE_URL}/user/search`)
    // 根据实际返回的数据结构调整
    salesmanList.value = response.data.data || response.data || []
  } catch (error) {
    ElMessage.error('获取业务员列表失败')
  } finally {
    loading.value = false
  }
}

// 获取用户是否在 合法用户中
const getCustomerList = async () => {
  loading.value = true
  try {
    const response = await axios.get(`${API_BASE_URL}/customer/CustomerRecords`)
    if(response.data.data.length!==0){
      customerList.value = response.data.data || response.data || []
    }else{
      ElMessage.warning('无进件客户')
    }
    // 根据实际返回的数据结构调整
  } catch (error) {
    ElMessage.error('获取客户列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索业务员
const handleSearch = async (query) => {
  if (query !== '') {
    loading.value = true
    try {
      const response = await axios.get(`${API_BASE_URL}/user/search`, {
        params: {
          name: query
        }
      })
      console.log('搜索结果:', response)
      // 根据实际返回的数据结构调整
      salesmanList.value = response.data.data || response.data || []
    } catch (error) {
      console.error('搜索业务员错误:', error)
      ElMessage.error('搜索业务员失败')
    } finally {
      loading.value = false
    }
  }
}

// 初始加载时获取所有业务员列表
onMounted(() => {
  // getSalesmanList()
  getCustomerList()
  console.log(
      provinceAndCityData,
      pcTextArr,
      regionData,
      pcaTextArr,
      codeToText,)
})

// 初始加载可以保留或删除
onMounted(() => {
  handleSearch('')
})
// const pcaTextArr = ref(null)
const formRef = ref(null)

const addressData = reactive({
  province: '',
  city: '',
  district: ''
})

const formData = reactive({
  // userId: '', // 改为存储业务员ID
  vehicleType: '',  //车辆类型
  customerName: '', //客户姓名
  idNumber: '', //身份证号码

  address: '', //户籍地址
  realAddress: '', //请选择实际居住地址
  detailAddress: '', //输入详细居住地址
  phoneNumber: '', //手机号码
  workUnit: '', //工作单位
  workplace: '', //请选择工作地址
  workDetailPlace: '',//请输入详情工作地址


  registrationPlace: '', //上牌地
  mileage: '', //里程数
  loanAmount: '',//贷款金额
  loanTerm: '', //贷款期限
  annualRate: '',//年利率
  coefficient: '', //万元系数
  monthlyPayment: '', //月供试算

  maritalStatus: '',//婚姻状况

  contactName: '', //亲友联系人姓名
  contactPhone: '', //亲友联系人电话
  contactRelation: '',//亲友联系人与客户关系
  otherContactName: '',//其他亲友联系人姓名
  otherContactPhone: '',//其他亲友联系人电话
  otherContactRelation: '',//其他亲友联系人与客户关系
  vinCode: '', //车架号
  driverPersonMsg: '',//驾驶证信息
  idCardPhotos: ["", ""], //身份证
  driverLicense: [], //驾驶证
  vehicleRegistration: [], //车辆登记证书
  vehicleLicense: [], //行驶证
  relationshipProof: [],//关系证明
  incomeProof: [],//收入证明
})
// 自定义验证函数，检查身份证图片数量是否为 2
const validateIdCardPhotos = (rule, value, callback) => {
  console.log(value)
  if (formData.idCardPhotos[0] == "") {
    callback(new Error('请上传身份证正反面照片'));
    return
  }
  if (formData.idCardPhotos[1] == "") {
    callback(new Error('请上传身份证正反面照片'));
    return
  }
  if (formData.idCardPhotos[0] !== "" && formData.idCardPhotos[1] !== "") {
    callback();
  } else {
    callback(new Error('请上传身份证正反两张照片'));
    return
  }
  // } else {
  //   callback(new Error('请上传身份证正反两张照片'));
  // }
};

// 校验居住地址选择，和详细地址输入
const validateAddress = (rule, value, callback) => {
  // 检查是否选择了省市区
  if (!selectedArea1.value || selectedArea1.value.length === 0) {
    callback(new Error('请选择实际居住地址'));
    return;
  }
  // 检查是否输入了详细地址
  if (!formData.detailAddress || formData.detailAddress.trim() === '') {
    callback(new Error('请输入详细地址'));
    return;
  }
  callback();
};

// 校验工作地点 ，和工作详情
const validateWorkPlace = (rule, value, callback) => {
  // 检查是否选择了省市区
  if (!selectedArea2.value || selectedArea2.value.length === 0) {
    callback(new Error('请选择工作地址'));
    return;
  }
  // 检查是否输入了详细地址
  if (!formData.workDetailPlace || formData.workDetailPlace.trim() === '') {
    callback(new Error('请输入详细工作地址'));
    return;
  }
  callback();
};

const rules = {
  // userId: [{required: true, message: '请选择业务员姓名'}],
  vehicleType: [{required: true, message: '请选择车辆类型'}],
  customerName: [{required: true, message: '请输入客户姓名'}],
  idNumber: [
    {required: true, message: '请输入证件号码'},
    {pattern: /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/, message: '请输入正确的身份证号'}
  ],
  address: [{required: true, message: '请输入客户户籍地址'}],
  realAddress: [
    {required: true,validator: validateAddress, trigger: ['change', 'blur']}
  ],
  // detailAddress: [{ required: true, message: '请输入详细居住地址' }],
  phoneNumber: [
    {required: true, message: '请输入手机号'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号'}
  ],
  workUnit: [{required: true, message: '请输入工作单位'}],
  workplace: [{required: true,validator: validateWorkPlace, trigger: ['change', 'blur']}],
  // workDetailPlace: [{required: true, message: '请输入详细工作地址'}],
  monthlyIncome: [{required: true, message: '请输入本月收入'},
    {
      validator: (rule, value, callback) => {
        if (isNaN(value) || Number(value) < 0) {
          callback(new Error('请输入大于0的数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  registrationPlace: [{required: true, message: '请输入上牌地'}],
  mileage: [
    {required: true, message: '请输入公里数'},
    {
      validator: (rule, value, callback) => {
        if (isNaN(value) || Number(value) < 0) {
          callback(new Error('请输入大于0的数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  loanAmount: [
    {required: true, message: '请输入贷款金额'},
    {
      validator: (rule, value, callback) => {
        if (isNaN(value) || Number(value) < 0) {
          callback(new Error('请输入大于0的数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],

  loanTerm: [
    {required: true, message: '请输入贷款期数'},
    {
      validator: (rule, value, callback) => {
        if (isNaN(value) || Number(value) < 0) {
          callback(new Error('请输入大于0的数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],
  annualRate: [
    {required: true, message: '请输入年利率'},
    {
      validator: (rule, value, callback) => {
        if (isNaN(value) || Number(value) < 0) {
          callback(new Error('请输入大于0的数字'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ],


  // coefficient: [{required: true, message: '请输入万元系数'}],  //计算出来的值
  // monthlyPayment: [{required: true, message: '请输入月供试算'}],//计算出来的值

  maritalStatus: [{required: true, message: '请选择婚姻状况'}],

  contactName: [{required: true, message: '请输入亲友联系人姓名'}],
  contactPhone: [
    {required: true, message: '请输入亲友联系人手机号'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号'}
  ],
  contactRelation: [{required: true, message: '请选择亲友联系与客户关系'}],

  otherContactName:[{required: true, message: '其他亲友联系人姓名'}],
  otherContactPhone: [
    {required: true, message: '请输入其他亲友联系人手机号'},
    {pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号'}
  ],
  otherContactRelation: [{required: true, message: '请选择其他亲友联系人与客户关系'}],

  driverPersonMsg: [{required: true, message: '请选择驾驶证信息'}],
  idCardPhotos: [
    {validator: validateIdCardPhotos, trigger: 'change'}
  ],
  driverLicense: [{required: true, message: '请上传驾驶证'}],
  vehicleRegistration: [{required: true, message: '请上传车辆登记证书'}],
  vehicleLicense: [{required: true, message: '请上传车辆行驶证'}],
}

// 验证车架号
const checkVinCode = async () => {
  // 调用上传文件接口
  const res = await axios.get(`${API_BASE_URL}/car-assessment/checkVinCode/` + formData.vinCode)
  if (res.data.code == 200) {
    if (res.data.data) {
    } else {
      ElMessage.warning('不存在当前车架号')
    }
  } else {
    ElMessage.warning(res.data.message)
  }
}

// 居住地址选择
// 在 script 中添加相关代码
const selectedArea1 = ref([]) // 用于存储选择的地区编码
const handleAreaChange1 = (value) => {
  formData.realAddress = selectedArea1.value.toString()
}

// 工作地址选择
const selectedArea2 = ref([]) // 用于存储选择的地区编码
const handleAreaChange2 = (value) => {
  formData.workplace = selectedArea2.value.toString()
}
// 万元系数、月供试算
const calculateLoanParams = async () => {
  if (!formData.loanAmount || !formData.loanTerm || !formData.annualRate) {
    formData.coefficient = ""
    formData.monthlyPayment = ""
    return;
  }
  try {
    const response = await axios.get(`${API_BASE_URL}/ocr/loan/calculate`, {
      params: {
        loanAmount: formData.loanAmount,
        loanTermMonths: formData.loanTerm,
        annualRate: formData.annualRate / 100  // 将百分比转换为小数
      }
    });

    if (response.data.code === 200) {
      formData.coefficient = response.data.data.coefficient;
      formData.monthlyPayment = response.data.data.monthlyPayment;
    } else {
      ElMessage.warning(response.data.message);
    }
  } catch (error) {
    ElMessage.error('计算贷款参数失败');
    console.error('计算贷款参数错误:', error);
  }
}

const updata = async () => {


}
const uploadRef0 = ref(null)
// 身份证正面
const handleUploadSuccess0 = async (response, file, fileList) => {
  const loading = ElLoading.service({
    lock: true,
    text: '图片上传中......',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const formDataOcr = new FormData()
  formDataOcr.append('file', response.raw)
  try {
    const resOcr = await axios.post(`${API_BASE_URL}/ocr/idCard`, formDataOcr, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (resOcr.data.code == 200) {
      // formData.customerName = resOcr.data.data.name
      // formData.idNumber = resOcr.data.data.idNum
      // formData.address = resOcr.data.data.address

      /*2025.8.9修改*/
      const name = resOcr.data.data.name;
      const idNum = resOcr.data.data.idNum;
      const matchedItem = customerList.value.find(item =>
          item.custName === name && item.idCar === idNum
      );

      if (matchedItem) {
        // 都满足，正常执行
        formData.customerName = name;
        formData.idNumber = idNum;
        formData.address = resOcr.data.data.address;
        // ElMessage.success('当前用户可以进件');

      } else {
        const nameMatch = customerList.value.some(item => item.custName === name);
        const idNumMatch = customerList.value.some(item => item.idCar === idNum);

        if (!nameMatch && !idNumMatch) {
          // 都不满足
          ElMessage.warning('当前用户无法进件');
          formData.customerName = '';
          formData.idNumber = '';
          formData.address = '';
          if (uploadRef0.value) {
            uploadRef0.value.clearFiles();
          }
          loading.close();
          return;
        } else if (!nameMatch) {
          // name 不满足
          ElMessage.warning('请修改名字');
          formData.idNumber = idNum
          formData.address = resOcr.data.data.address;
        } else if (!idNumMatch) {
          // idNum 不满足
          ElMessage.warning('请修改身份证');
          formData.customerName = name;
          formData.address = resOcr.data.data.address;
        }
      }
      /*2025.8.9修改*/



      const formDataList = new FormData()
      formDataList.append('files', response.raw)

      const res = await axios.post(`${API_BASE_URL}/customer/upload`, formDataList, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })

      if (res.data.code == 200) {
        const path = res.data.data[0]
        formData.idCardPhotos[0] = path
        loading.close()
        ElMessage.success('身份证照片上传成功')
      } else {
        loading.close()
        throw new Error(res.data.message || '上传失败')
      }
    } else {
      // const uploadRef = document.querySelector('.upload-demo')?.__vue__?.uploadRef
      // if (uploadRef) {
      //   uploadRef.clearFiles()
      // }
      if (uploadRef0.value) {
        uploadRef0.value.clearFiles()
      }
      loading.close()
      ElMessage.warning(resOcr.data.message)
    }
  } catch (error) {
    // 清空上传框
    // 在捕获异常时关闭 loading
    loading.close()
    ElMessage.error('请求出错: ' + (error.message || '未知错误'))
  }
}
// 身份证正面删除处理
// 身份证正面删除处理
const handleRemoveFile0 = (file, fileList) => {
  formData.idCardPhotos[0] = ""
  // 清空OCR识别的信息
  formData.customerName = ""
  formData.idNumber = ""
  formData.address = ""
  ElMessage.success('已删除身份证正面照片')
}
const handleExceed0 = (files, uploadFiles) => {
  ElMessage.warning('最多上传一张图片')
}


// 身份证
const handleUploadSuccess1 = async (response, file, fileList) => {
  const formDataList = new FormData()
  const formDataOcr = new FormData()
  formDataList.append('files', response.raw)
  formDataOcr.append('files', response.raw)
  const res = await axios.post(`${API_BASE_URL}/customer/upload`, formDataList, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  if (res.data.code == 200) {
    // 假设接口返回的完整路径字段名为 fullPath
    const path = res.data.data[0]
    // 将完整路径添加到数组中
    formData.idCardPhotos[1] = path
    ElMessage.success('身份证照片上传成功')
  } else {
    ElMessage.warning(res.data.message)
  }
}
// 身份证反面删除处理
// 身份证反面删除处理
const handleRemoveFile1 = (file, fileList) => {
  // 使用filter方法确保只删除对应的文件路径
  formData.idCardPhotos[1] = ""
  ElMessage.success('已删除身份证反面照片')
}
const handleExceed1 = (files, uploadFiles) => {
  ElMessage.warning('最多上传一张图片')
}

// 行驶证
const handleUploadSuccess2 = async (response, file, fileList) => {
  const formDataList = new FormData()
  formDataList.append('files', response.raw)
  const res = await axios.post(`${API_BASE_URL}/customer/upload`, formDataList, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  if (res.data.code == 200) {
    // 假设接口返回的完整路径字段名为 fullPath
    const path = res.data.data[0]
    // 将完整路径添加到数组中
    formData.driverLicense.push(path)
    ElMessage.success('行驶证上传成功')
  } else {
    ElMessage.warning(res.data.message)
  }
}
// 删除文件时的处理函数
const handleRemoveFile2 = (file, fileList) => {
  const fileIndex = fileList.indexOf(file)
  if (fileIndex > -1) {
    // 从数组中移除对应的完整路径
    formData.driverLicense.value.splice(fileIndex, 1)
  }
  ElMessage.success('已删除行驶证照片')
}
const handleExceed2 = (files, uploadFiles) => {
  ElMessage.warning('最多上传一张图片')
}

// 车辆登记证书
const handleUploadSuccess3 = async (response, file, fileList) => {
  const formDataList = new FormData()
  formDataList.append('files', response.raw)
  const res = await axios.post(`${API_BASE_URL}/customer/upload`, formDataList, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  if (res.data.code == 200) {
    // 假设接口返回的完整路径字段名为 fullPath
    const path = res.data.data[0]
    // 将完整路径添加到数组中
    formData.vehicleRegistration.push(path)
    ElMessage.success('车辆登记证书上传成功')
  } else {
    ElMessage.warning(res.data.message)
  }
}
// 删除文件时的处理函数
const handleRemoveFile3 = (file, fileList) => {
  const fileIndex = fileList.indexOf(file)
  if (fileIndex > -1) {
    // 从数组中移除对应的完整路径
    formData.vehicleRegistration.value.splice(fileIndex, 1)
  }
  ElMessage.success('已删除车辆登记证书')
}
const handleExceed3 = (files, uploadFiles) => {
  ElMessage.warning('最多上传一张图片')
}


// 车辆行驶证
const uploadRef4 = ref(null)
const handleUploadSuccess4 = async (response, file, fileList) => {
  const loading = ElLoading.service({
    lock: true,
    text: '图片上传中......',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  const formDataOcr = new FormData()
  formDataOcr.append('file', response.raw)
  try {
    const resOcr = await axios.post(`${API_BASE_URL}/ocr/vehicleLicense`, formDataOcr, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    })

    if (resOcr.data.code == 200) {
      formData.vinCode = resOcr.data.data
      const formDataList = new FormData()
      formDataList.append('files', response.raw)
      const res = await axios.post(`${API_BASE_URL}/customer/upload`, formDataList, {
        headers: {
          'Content-Type': 'multipart/form-data'
        }
      })
      if (res.data.code == 200) {
        // 假设接口返回的完整路径字段名为 fullPath
        const path = res.data.data[0]
        // 将完整路径添加到数组中
        formData.vehicleLicense.push(path)
        loading.close()
        ElMessage.success('车辆行驶证上传成功')
      } else {
        loading.close()
        ElMessage.warning(res.data.message)
      }
    } else {
      if (uploadRef4.value) {
        uploadRef4.value.clearFiles()
      }
      loading.close()
      ElMessage.warning(resOcr.data.message)
    }
  } catch (error) {
    loading.close()
    ElMessage.warning(error.message)
  }


}
// 删除文件时的处理函数
const handleRemoveFile4 = (file, fileList) => {
  const fileIndex = fileList.indexOf(file)
  if (fileIndex > -1) {
    // 从数组中移除对应的完整路径
    formData.vinCode = ""
    formData.vehicleLicense.value.splice(fileIndex, 1)
  }
  ElMessage.success('已删除车辆行驶证')
}
const handleExceed4 = (files, uploadFiles) => {
  ElMessage.warning('最多上传一张图片')
}


// 证明关系
const handleUploadSuccess5 = async (response, file, fileList) => {
  const formDataList = new FormData()
  formDataList.append('files', response.raw)
  const res = await axios.post(`${API_BASE_URL}/customer/upload`, formDataList, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  if (res.data.code == 200) {
    // 假设接口返回的完整路径字段名为 fullPath
    const path = res.data.data[0]
    // 将完整路径添加到数组中
    formData.relationshipProof.push(path)
    ElMessage.success('证明关系上传成功')
  } else {
    ElMessage.warning(res.data.message)
  }
}
// 删除文件时的处理函数
const handleRemoveFile5 = (file, fileList) => {
  const fileIndex = fileList.indexOf(file)
  if (fileIndex > -1) {
    // 从数组中移除对应的完整路径
    formData.relationshipProof.value.splice(fileIndex, 1)
  }
  ElMessage.success('已删除证明关系')
}
const handleExceed5 = (files, uploadFiles) => {
  ElMessage.warning('最多上传一张图片')
}

// 收入证明
const handleUploadSuccess6 = async (response, file, fileList) => {
  const formDataList = new FormData()
  formDataList.append('files', response.raw)
  const res = await axios.post(`${API_BASE_URL}/customer/upload`, formDataList, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
  })
  if (res.data.code == 200) {
    // 假设接口返回的完整路径字段名为 fullPath
    const path = res.data.data[0]
    // 将完整路径添加到数组中
    formData.incomeProof.push(path)
    ElMessage.success('收入证明上传成功')
  } else {
    ElMessage.warning(res.data.message)
  }
}
// 删除文件时的处理函数
const handleRemoveFile6 = (file, fileList) => {
  const fileIndex = fileList.indexOf(file)
  if (fileIndex > -1) {
    // 从数组中移除对应的完整路径
    formData.incomeProof.value.splice(fileIndex, 1)
  }
  ElMessage.success('已删除收入证明')
}
const handleExceed6 = (files, uploadFiles) => {
  ElMessage.warning('最多上传一张图片')
}


const submitLoading = ref(false)

// 提交按钮
const submitForm = async () => {
  submitLoading.value = true
  if (!formRef.value){
    submitLoading.value = false
    return
  }
  try {
    await formRef.value.validate()
    // TODO: 实现表单提交逻辑
    const res = await axios.post(`${API_BASE_URL}/customer/save`, formData).catch(err => {
      submitLoading.value = false
    })
    if (res.data.code == 200) {
      ElMessage.success('提交成功')
      formRef.resetFields()
      submitLoading.value = false
    } else {
      ElMessage.warning(res.data.message)
      submitLoading.value = false
    }
  } catch (error) {
    submitLoading.value = false
    // ElMessage.error('请检查表单填写是否正确')
  }
}

const backHome = () => {
  router.push({path: '/menu'})
}


</script>

<style lang="scss">
.train-tree {
  .el-cascader-panel {
    /*background-color: #103d69 !important;
    color: #4388c1 !important;*/
  }
/*  .el-cascader-node:not(.is-disabled):focus,
  .el-cascader-node:not(.is-disabled):hover {
    color: var(--el-cascader-menu-selected-text-color) !important;
  }*/
  .el-cascader-menu{
    min-width: unset !important;
  }
  .el-cascader-menu__wrap.el-scrollbar__wrap{
    width: 110px;
  }
  .el-cascader-menu__list {
    li {
      /*
      color: #4388c1 !important;
      */
      span {
        display: inline-block;
        /* 可以添加其他样式，如宽度、边距、填充等 */
      }
    }
    .el-cascader-node {
      padding: 0 2px !important;
    }
    .el-cascader-node__label{
      padding: 0 0 !important;
    }
  }
/*  .el-cascader-node:not(.is-disabled):focus,
  .el-cascader-node:not(.is-disabled):hover {
    background-color: #9badbf !important;
  }*/
}
</style>


<style scoped>
.realClass :deep(.el-cascader-menu) {
  width: unset !important;
}
.realClass :deep(.el-cascader-menu .el-cascader-node) {
  padding: 0 2px !important;
}

.loan-form {
  padding: 0 0;
}

.loan-form-container {
  max-width: 800px;
  margin: 0 auto;
}

.el-divider {
  margin: 24px 0;
}

.upload-demo {
  text-align: left;
}
</style>
